import serial
import time
import json

class pi_esp32_serial:

    def __init__(self):
        # setup serial
        self.ser = serial.Serial(
            port='/dev/serial0',  # Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
            baudrate=9600,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1
        )
        self.serial_ready = True
        self.received = None
        self.received_ok = False

    def read_message(self):
        try:
            if self.ser.in_waiting > 0:
                received_bytes = self.ser.readline()
                try:
                    received_json_string = received_bytes.decode(
                        'utf-8').rstrip()
                    self.received = json.loads(received_json_string)
                    # print(f"From ESP32: {self.received}")
                    self.received_ok = True
                except:
                    self.received_ok = False
        except:
            self.received_ok = False

    def send_message(self, cmd):
        self.ser.write((cmd + '\n').encode('utf-8'))
        # print(f"response: {cmd}")


if __name__ == "__main__":
    ser_comm = pi_esp32_serial()
    while True:
        # read esp32
        ser_comm.send_message("STOP")
        ser_comm.read_message()
        time.sleep(0.1)
